from flask import Flask
from flask import jsonify
from pandas import read_excel
from numpy import array, reshape, integer, floating, ndarray
from json import dumps, loads, JSONEncoder
from flask import request
from demjson import decode
from joblib import load  # 直接导入，已经从sklearn中独立

app = Flask(__name__)


# 作用      获取360个传感器温度值
# 方法      GET
# return   "{"input": [23.889, 、、、]}"
# url       http://127.0.0.1:9999/getInput?index=1
@app.route('/getInput', methods=['GET'])
def get_json():
    index = int(request.args.get('index'))
    print(index)
    if index == None:
        index = 0
    print("============获取360个传感器温度值=============")
    dataset = read_excel('../../data/newData.xlsx')
    # 要分析的数据
    X = dataset.iloc[5:, 1:360].values
    # 转置
    X_index = [[row[i] for row in X] for i in range(len(X[0]))]
    X_index = array(X_index)
    # 输入数据
    x = x = array(X_index)
    # 字典
    inputDate = {"input": [0] * 360}
    inputDate['input'] = x[index]
    input_x = dumps(inputDate, cls=NpEncoder)
    print()
    print("输入数据为:%s" % (input_x))
    print("输入数据的尺寸为：%s" % (array(x[1]).shape))
    return jsonify(input_x)


# 作用      清液层和絮凝层分界面预测
# 方法      POST
# 接收数据  "{"input": [23.889, 、、、]}"
# return   "{\"predict\": 8.008390287276542}"
# url       http://127.0.0.1:9999/predict
@app.route('/predict', methods=['POST'])
def post_json():
    print("=========清液层和絮凝层分界面预测===========")
    data = request.get_data()
    data = loads(data)
    data = decode(data)
    input = data['input']
    print("输入数据为：%s" % (input))
    # 预测
    predict_value = predict(input)
    # 字典
    date = {"predict": 123}
    date['predict'] = predict_value[0][0]
    date_json = dumps(date)
    print("预测结果为：%s" % (date_json))
    return jsonify(date_json)


class NpEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, integer):
            return int(obj)
        elif isinstance(obj, floating):
            return float(obj)
        elif isinstance(obj, ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)


def predict(x):
    x_pred = reshape(x, (1, -1))
    num_of_index = 1
    for i in range(num_of_index):
        gbr = load(modelName)
        test_y = gbr.predict(x_pred)
    test_y = reshape(test_y, (1, -1))
    return test_y


modelName = "q_train_model_0_result.m40"
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=9999)
